package org.example.journal_items.service.impl;

import org.example.journal_items.common.Result;
import org.example.journal_items.common.ResultCode;
import org.example.journal_items.Entity.User;
import org.example.journal_items.service.UserService;
import org.example.journal_items.UserDao.UserDao;
import org.example.journal_items.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.HashMap;
import java.util.Map;
import java.util.Base64;
import java.io.IOException;

@Service
public class UserServiceImpl implements UserService {

  @Autowired
  private PasswordEncoder passwordEncoder;

  @Autowired
  private JwtUtil jwtUtil;

  @Autowired
  private UserDao userDao;

  @Override
  public Result login(String username, String password) {
    User user = userDao.findByUsername(username);
    if (user == null) {
      return Result.error("用户名不存在");
    }

    if (passwordEncoder.matches(password, user.getPassword())) {
      String token = jwtUtil.generateToken(username);
      Map<String, Object> result = new HashMap<>();
      result.put("token", token);
      result.put("user", user);
      return Result.success("登录成功", result);
    }
    return Result.error("密码错误");
  }

  @Override
  public Result register(User user) {
    User existingUser = userDao.findByUsername(user.getUsername());
    if (existingUser != null) {
      return Result.error("用户名已存在");
    }

    // 对密码进行加密
    String encodedPassword = passwordEncoder.encode(user.getPassword());
    user.setPassword(encodedPassword);
    user.setIsFirstLogin(true); // 新注册用户首次登录

    userDao.insertUser(user);
    return Result.success("注册成功");
  }

  @Override
  public Result checkUsername(String username) {
    User user = userDao.findByUsername(username);
    System.out.println("Debug: User found by findByUsername: " + user);
    if (user == null) {
      return Result.success("用户名可用", true);
    } else {
      return Result.success("用户名已被使用", false);
    }
  }

  @Override
  public User getUserById(Long userId) {
    return userDao.findById(userId);
  }

  @Override
  public void updateAvatar(Long userId, String avatar) {
    userDao.updateAvatar(userId, avatar);
  }

  @Override
  public String uploadAvatar(Long userId, MultipartFile file) throws Exception {
    try {
      // 读取文件内容并转换为Base64编码
      byte[] fileContent = file.getBytes();
      String base64String = Base64.getEncoder().encodeToString(fileContent);

      // 获取文件类型
      String contentType = file.getContentType();
      String dataUrl = "data:" + contentType + ";base64," + base64String;

      // 更新用户头像
      userDao.updateAvatar(userId, dataUrl);

      return dataUrl;
    } catch (IOException e) {
      throw new Exception("文件读取失败: " + e.getMessage());
    }
  }

  @Override
  public Result updateUserInfo(User user) {
    user.setIsFirstLogin(false); // 完善资料后不再是首次登录
    userDao.updateUserInfo(user);
    return Result.success("用户信息更新成功");
  }

  @Override
  public Result logout() {
    return Result.success("登出成功");
  }

  @Override
  public String getUserTheme(Long userId) {
    User user = userDao.findById(userId);
    return user != null ? user.getTheme() : "star";
  }

  @Override
  public Result updateUserTheme(Long userId, String theme) {
    userDao.updateUserTheme(userId, theme);
    return Result.success("主题更新成功");
  }
}